package com.twu.biblioteca.util;

import com.google.inject.Inject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ConsoleReader {
  private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  private ConsoleWriter writer;

  @Inject
  public void setWriter(ConsoleWriter writer) {
    this.writer = writer;
  }

  public int readLineAndConvertInt(int itemSize, String errorMessage) {
    String line = null;
    int item;
    while (true) {
      try {
        line = br.readLine();
        item = Integer.parseInt(line);
        if (item > 0 && item <= itemSize) {
          break;
        } else {
          writer.display(String.format(errorMessage, itemSize));
        }
      } catch (Exception e) {
        writer.display(String.format(errorMessage, itemSize));
      }
    }
    return item;
  }

  public String readLine() {
    try {
      return br.readLine();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
}
